package com.agrimall.servlet.client;

import com.agrimall.entity.Product;
import com.agrimall.entity.Review;
import com.agrimall.entity.User;
import com.agrimall.service.ProductService;
import com.agrimall.service.ReviewService;
import com.agrimall.service.impl.ProductServiceImpl;
import com.agrimall.service.impl.ReviewServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户端商品管理Servlet
 */
@WebServlet("/client/product")
public class ProductServlet extends HttpServlet {
    private ProductService productService = new ProductServiceImpl();
    private ReviewService reviewService = new ReviewServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if (action == null || action.equals("") || action.equals("list")) {
            // 商品列表
            listProducts(request, response);
        } else if (action.equals("detail")) {
            // 商品详情
            productDetail(request, response);
        } else if (action.equals("checkBalance")) {
            // 校验余额（用于购买前检查）
            checkBalance(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        
        if (action != null && action.equals("purchase")) {
            // 购买商品
            purchaseProduct(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    /**
     * 商品列表
     */
    private void listProducts(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String pageStr = request.getParameter("page");
            String category = request.getParameter("category");
            String keyword = request.getParameter("keyword");
            
            int page = 1;
            if (pageStr != null && !pageStr.isEmpty()) {
                try {
                    page = Integer.parseInt(pageStr);
                } catch (NumberFormatException e) {
                    page = 1;
                }
            }
            int pageSize = 12;
            
            List<Product> products;
            int totalCount = 0;
            try {
                if (keyword != null && !keyword.isEmpty()) {
                    products = productService.searchProducts(keyword, page, pageSize);
                    totalCount = productService.countProductsByKeyword(keyword);
                } else if (category != null && !category.isEmpty()) {
                    products = productService.getProductListByCategory(category, page, pageSize);
                    totalCount = productService.countProductsByCategory(category);
                } else {
                    products = productService.getProductList(page, pageSize);
                    totalCount = productService.countAllProducts();
                }
                
                if (products == null) {
                    products = new java.util.ArrayList<>();
                }
            } catch (Exception e) {
                e.printStackTrace();
                products = new java.util.ArrayList<>();
                request.setAttribute("error", "查询商品失败：" + e.getMessage());
            }
            
            // 计算总页数
            int totalPages = totalCount > 0 ? (int) Math.ceil((double) totalCount / pageSize) : 1;
            boolean hasNextPage = page < totalPages;
            
            request.setAttribute("products", products);
            request.setAttribute("page", page);
            request.setAttribute("totalCount", totalCount);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("hasNextPage", hasNextPage);
            request.setAttribute("category", category);
            request.setAttribute("keyword", keyword);
            request.getRequestDispatcher("/client/product/list.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "数据加载失败：" + e.getMessage());
            request.getRequestDispatcher("/client/product/list.jsp").forward(request, response);
        }
    }
    
    /**
     * 商品详情
     */
    private void productDetail(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String productIdStr = request.getParameter("id");
        if (productIdStr == null) {
            response.sendRedirect(request.getContextPath() + "/client/index");
            return;
        }
        
        try {
            Long productId = Long.parseLong(productIdStr);
            Product product = productService.getProductById(productId);
            
            if (product == null) {
                response.sendRedirect(request.getContextPath() + "/client/index");
                return;
            }
            
            // 获取该商品的评论列表（前10条）
            List<Review> reviews = reviewService.getReviewListByProduct(productId, 1, 10);
            
            request.setAttribute("product", product);
            request.setAttribute("reviews", reviews);
            request.getRequestDispatcher("/client/product/detail.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "数据加载失败：" + e.getMessage());
            request.getRequestDispatcher("/client/index.jsp").forward(request, response);
        }
    }
    
    /**
     * 校验余额（GET请求）
     */
    private void checkBalance(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        HttpSession session = request.getSession();
        com.agrimall.entity.User user = (com.agrimall.entity.User) session.getAttribute("user");
        
        if (user == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
            return;
        }
        
        try {
            String productIdStr = request.getParameter("productId");
            String quantityStr = request.getParameter("quantity");
            
            if (productIdStr == null || quantityStr == null) {
                result.put("success", false);
                result.put("message", "参数错误");
                out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
                return;
            }
            
            Long productId = Long.parseLong(productIdStr);
            Integer quantity = Integer.parseInt(quantityStr);
            
            Product product = productService.getProductById(productId);
            if (product == null) {
                result.put("success", false);
                result.put("message", "商品不存在");
                out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
                return;
            }
            
            BigDecimal totalAmount = product.getPrice().multiply(new BigDecimal(quantity));
            com.agrimall.service.UserService userService = new com.agrimall.service.impl.UserServiceImpl();
            BigDecimal userBalance = userService.getUserBalance(user.getUserId());
            if (userBalance == null) {
                userBalance = BigDecimal.ZERO;
            }
            
            result.put("success", true);
            result.put("balance", userBalance);
            result.put("totalAmount", totalAmount);
            result.put("sufficient", userBalance.compareTo(totalAmount) >= 0);
            
            out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
            out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
        }
    }
    
    /**
     * 购买商品
     */
    private void purchaseProduct(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        HttpSession session = request.getSession();
        com.agrimall.entity.User user = (com.agrimall.entity.User) session.getAttribute("user");
        
        if (user == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
            return;
        }
        
        try {
            request.setCharacterEncoding("UTF-8");
            
            String productIdStr = request.getParameter("productId");
            String quantityStr = request.getParameter("quantity");
            String paymentMethod = request.getParameter("paymentMethod");
            
            if (productIdStr == null || productIdStr.trim().isEmpty() || 
                quantityStr == null || quantityStr.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "参数错误：商品ID或数量为空");
                out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
                return;
            }
            
            Long productId = Long.parseLong(productIdStr);
            Integer quantity = Integer.parseInt(quantityStr);
            
            Product product = productService.getProductById(productId);
            if (product == null) {
                result.put("success", false);
                result.put("message", "商品不存在");
                out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
                return;
            }
            
            if (product.getStock() < quantity) {
                result.put("success", false);
                result.put("message", "库存不足");
                out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
                return;
            }
            
            BigDecimal totalAmount = product.getPrice().multiply(new BigDecimal(quantity));
            
            com.agrimall.service.UserService userService = new com.agrimall.service.impl.UserServiceImpl();
            BigDecimal userBalance = userService.getUserBalance(user.getUserId());
            if (userBalance == null) {
                userBalance = BigDecimal.ZERO;
            }
            
            if (userBalance.compareTo(totalAmount) < 0) {
                result.put("success", false);
                result.put("message", "余额不足");
                result.put("balance", userBalance);
                result.put("totalAmount", totalAmount);
                out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
                return;
            }
            
            com.agrimall.service.OrderService orderService = new com.agrimall.service.impl.OrderServiceImpl();
            com.agrimall.entity.Order order = new com.agrimall.entity.Order();
            order.setUserId(user.getUserId());
            order.setMerchantId(product.getMerchantId());
            order.setTotalAmount(totalAmount);
            order.setDeliveryAddress(user.getAddress() != null ? user.getAddress() : "");
            order.setReceiverName(user.getRealName() != null ? user.getRealName() : user.getUsername());
            order.setReceiverPhone(user.getPhone() != null ? user.getPhone() : "");
            
            com.agrimall.entity.OrderItem orderItem = new com.agrimall.entity.OrderItem();
            orderItem.setProductId(product.getProductId());
            orderItem.setProductName(product.getProductName());
            orderItem.setProductImage(product.getImageUrl());
            orderItem.setPrice(product.getPrice());
            orderItem.setQuantity(quantity);
            orderItem.setSubtotal(totalAmount);
            
            List<com.agrimall.entity.OrderItem> orderItems = new java.util.ArrayList<>();
            orderItems.add(orderItem);
            
            String orderNo = orderService.createOrder(order, orderItems);
            
            if (orderNo != null) {
                if (paymentMethod != null && !paymentMethod.isEmpty()) {
                    boolean paySuccess = orderService.payOrder(orderNo, paymentMethod);
                    if (!paySuccess) {
                        result.put("success", false);
                        result.put("message", "支付失败，余额不足或订单状态异常");
                        out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
                        return;
                    }
                    
                    User updatedUser = userService.getUserById(user.getUserId());
                    if (updatedUser != null) {
                        session.setAttribute("user", updatedUser);
                    }
                }
                
                result.put("success", true);
                result.put("message", "购买成功");
                result.put("orderNo", orderNo);
            } else {
                result.put("success", false);
                result.put("message", "创建订单失败");
            }
            
            out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
            out.print(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
        }
    }
}

